package com.bw.base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.base.net.Res
import kotlinx.coroutines.launch

open class BaseViewModel:ViewModel() {
    fun <T> httpRequst(s:suspend ()-> Res<T>,
                   succse:suspend (T)->Unit){
        try {
            viewModelScope.launch {
                val res=s.invoke()
                if (res.code==200){
                    succse.invoke(res.data)
                }else{
                    Log.i("===",res.msg)
                }
            }
        }catch (e:Exception){
            Log.i("===",e.message.toString())
        }
    }
    fun <T> httpRequst2(s:suspend ()-> T,
                       succse:suspend (T)->Unit){
        viewModelScope.launch {
            try {
                val res=s.invoke()
                succse.invoke(res)

            }catch (e:Exception){
                Log.i("===",e.message.toString())
            }
        }
    }
    fun <T> roomRequst(s: ()-> T, succse: (T)->Unit){
        try {
            viewModelScope.launch {
                val res=s.invoke()
                if (res!=null){
                    succse.invoke(res)
                }else{
                    Log.d("===","操作失败")
                }
            }
        }catch (e:Exception){
            Log.i("===",e.message.toString())
        }
    }
}